package dao.impl;

import dao.IReplyDao;
import entity.Reply;
import entity.Topic;
import entity.Users;
import until.DButil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class ReplyDaoImpl extends DButil implements IReplyDao {

    Connection conn=null;
    PreparedStatement pst=null;
    ResultSet rs=null;

    @Override
    public int addReply(Reply reply) {
        conn=getCon();
        int len=0;
        try {
            String sql="insert into tb_reply" +
                    "(col_hcontext,col_hpic,col_htime,col_uid,col_fid,col_hdel) " +
                    "values(?,?,now(),?,?,1)";
            pst=conn.prepareStatement(sql);
            pst.setString(1,reply.getHcontext());
            pst.setString(2,reply.getHpic());
            pst.setInt(3,reply.getUid().getUid());
            pst.setInt(4,reply.getFid().getFid());
            len=pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            clsAll(conn,pst,null);
        }
        return len;
    }

    @Override
    public List getAll() {
        List list=new ArrayList();
        conn=getCon();
        try {

            String sql="SELECT * FROM " +
                    "tb_reply r,tb_user u,tb_topic t " +
                    "WHERE r.col_uid=u.col_uid AND r.col_fid=t.col_fid and r.col_hdel=1 ";
            pst=conn.prepareStatement(sql);
            rs=pst.executeQuery();
            while (rs.next()){
                Reply reply=new Reply();
               reply.setHid(rs.getInt("col_hid"));
               reply.setHcontext(rs.getString("col_hcontext"));
               reply.setHpic(rs.getString("col_hpic"));
               reply.setHtime(rs.getTime("col_htime"));
               reply.setUid(new Users(rs.getInt("col_uid"),rs.getString("col_uname")));
               reply.setFid(new Topic(rs.getInt("col_fid"),rs.getString("col_ftitle")));
               reply.setHdel(rs.getInt("col_hdel"));

               list.add(reply);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            clsAll(conn,pst,rs);
        }
        return list;
    }
}
